package com.gdou.service.impl;

import com.gdou.commons.Result;
import com.gdou.mapper.ShipMapper;
import com.gdou.mapper.UserMapper;
import com.gdou.dto.ShipDto;
import com.gdou.dto.ShipSaveDto;
import com.gdou.model.Ship;
import com.gdou.model.User;
import com.gdou.service.ShipService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class ShipServiceImpl implements ShipService {

    @Autowired
    private ShipMapper shipMapper;

    @Autowired
    private UserMapper userMapper;


    @Override
    public Result findShipsBySearch(ShipDto shipDto) {
        PageHelper.startPage(shipDto.getPageNum(),shipDto.getPageSize());
        List<Ship> shipList = shipMapper.selectBySearch(shipDto);
        PageInfo<Ship> pageInfo = new PageInfo<>(shipList);
        Result result = new Result();
        result.setData(pageInfo.getList());
        result.setTotal(pageInfo.getTotal());
        return result;
    }

    @Override
    public Result saveShip(ShipSaveDto shipSaveDto) {

        int rows = shipMapper.insertShip(shipSaveDto);
        if (rows<1){
            return new Result(-1,"添加船舶失败");
        }
        return new Result();
    }

    @Override
    public Result removeOne(Integer id) {
        int rows = shipMapper.deleteOne(id);
        if (rows<1){
            return new Result(-1,"删除失败");
        }

        /*将该船的关联成员 数据修改：ship_id 置空 或者 其他值*/
        rows = userMapper.updateUserShip_idNull(id);

        return new Result();
    }

    @Override
    public Result removeMany(String ids) {
        int rows = shipMapper.deleteMany(ids);
        if (rows<1){
            return new Result(-1,"批量删除失败");
        }
        return new Result();
    }

    @Override
    public Result modifyShip(ShipSaveDto shipSaveDto) {

        int rows = shipMapper.updateShip(shipSaveDto);
        if (rows<1){
            return new Result(-1,"船舶修改失败");
        }

        return new Result();
    }

    @Override
    public Result findShipUserList(Long id) {
        List<User> userList = userMapper.selectUsersByShipId(id);
        Result result = new Result();
        result.setData(userList);
        return result;
    }

    @Override
    public Result findAllShip() {

        List<Ship> shipList = shipMapper.selectAll();

        Result result = new Result();
        result.setData(shipList);
        return result;
    }
}
